package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fdoj.eventInvitations.dao.CommentDao;
import fdoj.eventInvitations.dao.EventDao;
import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Comment;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Person;

public class AddCommentController extends HttpServlet{
	@EJB
	private EventDao eventDao;
	@EJB
	private CommentDao commentDao;
	@EJB
	private PersonDao personDao;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
			Person person = (Person) request.getSession().getAttribute("loggedUser");
			if (person == null) {
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
			String text= request.getParameter("text");
			String event_id = request.getParameter("event_id");
			Comment comment = new Comment();
			comment.setText(text);
			comment.setDate(new Date());
			Event event = eventDao.findById(Integer.parseInt(event_id));
			person.addComment(comment);
			event.addComment(comment);
			eventDao.merge(event);
			
			response.sendRedirect(response.encodeRedirectURL("./home"));	
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}
